import { Injectable, NestInterceptor, CallHandler, ExecutionContext, HttpStatus } from '@nestjs/common'
import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { Response } from 'express'

/**
 * 统一返回结果拦截器
 */
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Result.data<T>> {
  intercept(context: ExecutionContext, next: CallHandler<any>): Observable<Result.data<T>> {
    return next.handle().pipe(
      map((data) => {
        const res = context.switchToHttp().getResponse() as Response
        return {
          statusCode: res.statusCode,
          data,
          message: '请求成功',
          time: new Date().toLocaleString(),
        }
      }),
    )
  }
}
